<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2016/9/30
 * Time: 14:33
 */
namespace App\Http\Controllers\admin_system;

use App\Common\ApiData;
use App\Models\V1\CompanyModel;
use Faker\Provider\lt_LT\Company;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Module\EntMemberInfo;
use App\Module\EntMemberDRP;
use SimpleSoftwareIO\QrCode\BaconQrCodeGenerator;
use Illuminate\Support\Facades\Input;
use Storage,Cookie,DB,Validator,Redirect,Session,Excel;
use Illuminate\Database\Query;
use App\Models\V1\MemberModel;



class MemberController extends Controller
{

    public function check_role($request){
        $manageUser = session('manageUser');
        $uri = $request->server('REQUEST_URI');
        //以下内容不能让普通游客进入
        $uris = [
            '/\/admin_system\/memberdrp\/indexAdd/',
            '/\/admin_system\/memberdrp\/indexAddTwo/',
            '/\/admin_system\/memberdrp\/index\/\d+\/edit/',
            '/\/admin_system\/memberdrp\/indexDelete/',
            '/\/admin_system\/member\/indexAdd/',
            '/\/admin_system\/member\/index\/\d+\/edit/',
            '/\/admin_system\/member\/indexDelete/',
        ];
        if($manageUser && $manageUser->role != 1){
            foreach($uris as $u){
                if(preg_match($u,$uri)){
                    exit('<script>alert("权限不足!");history.back();</script>');
                }
            }
        }
    }


    /**
     * 会员列表
     * */
    public function index(Request $request,$keyword = '')
    {
        $data = $this->get_index_data($request,$keyword);
        return view('admin_system.member.index',$data);
    }




    public function get_index_data($request,$keyword = '',$needDrp = true){
        /** 会员状态 0.表示未激活 1.表示激活 2.表示所有** */
        $memberType     = $request->input('memberType',2);
        $registerType   = $request->input('registerType','');
        $companyId      = $request->input('companyId',0);

        //注册的用户类型
        switch($memberType){
            case 0:
                $condition = ['States','=',0];
                break;
            case 1;
                $condition = ['States','=',1];
                break;
            case 2:
                $condition = ['States','<',2];
                break;
        }

        $condition = [$condition];
        if($registerType == 2){
            array_push($condition,['RegisterType','=',2]);
        }

        $colum = [
            'UserID',
            'MemNumber',
            'NickName',
            'UserName',
            'YourName',
            'MemEndTime',
            'States',
            'DeleteMark',
            'ReleaseDate',
            'AddDate',
        ];

        $entMemberInfo = DB::table('MemberInfo')
            ->select($colum)
            ->where('DeleteMark','1')
            ->where($condition);


        if ($keyword != '') {
            $entMemberInfo = $entMemberInfo->where(function ($query) use ($keyword) {
                    $query->orwhere('NickName', 'like', '%' . $keyword . '%')
                        ->orwhere('YourName', 'like', '%' . $keyword . '%')
                        ->orwhere('UserName', 'like', '%' . $keyword . '%')
                        ->orwhere("MemNumber",$keyword);
                });
        }

        if($companyId > 0){
            $entMemberInfo->where('company_id',$companyId);
        }

        $entMemberInfo = $entMemberInfo->orderBy('ReleaseDate', 'desc')->paginate(20);

        //获取每个会员的学习官
        if($needDrp){
            foreach($entMemberInfo as $key => $v){
                $memNumber = $v->MemNumber;
                $parentId = DB::table('memberdrp')->where('MemNumber',$memNumber)->value('ParentID');

                $entMemberInfo[$key]->parentId      = '';
                $entMemberInfo[$key]->parentName    = '';

                if(empty($parentId)){
                    continue;
                }

                $SQL = "  SELECT b.YourName,a.DRPID
                      FROM memberdrp a
                      LEFT JOIN memberinfo b ON b.MemNumber = a.MemNumber
                      WHERE a.DRPID = '{$parentId}' ";
                $parentInfo = DB::select($SQL);

                foreach($parentInfo as $p){
                    $entMemberInfo[$key]->parentId      = $p->DRPID;
                    $entMemberInfo[$key]->parentName    = $p->YourName;
                }
            }
        }
        return [
            'entMemberInfo' => $entMemberInfo,
            'keyword'       => $keyword,
            'memberType'    => $memberType,
            'registerType'  => $registerType,
            'companyId'     => $companyId
        ];
    }

    public function indexTwo($keyword = '')
    {
       if ($keyword != '') {
            $entMemberInfo = DB::table('MemberInfo')->select('UserID', 'MemNumber', 'NickName', 'UserName', 'YourName', 'MemEndTime', 'States', 'DeleteMark', 'ReleaseDate', 'AddDate')
                ->where('DeleteMark', '1')
                ->where('RegisterType', 2)
                ->where(function ($query) use ($keyword) {
                    $query->orwhere('NickName', 'like', '%' . $keyword . '%')
                        ->orwhere('YourName', 'like', '%' . $keyword . '%')
                        ->orwhere('UserName', 'like', '%' . $keyword . '%');
                })
                ->orderBy('ReleaseDate', 'desc')
                ->paginate(20);

        } else {
            $entMemberInfo = DB::table('MemberInfo')->select('UserID', 'MemNumber', 'UserName', 'YourName', 'MemEndTime', 'States', 'DeleteMark', 'ReleaseDate', 'AddDate')
                ->where('DeleteMark', '1')
                ->where('RegisterType', 2)
                ->orderBy('ReleaseDate', 'desc')
                ->paginate(20);
        }



        return view('admin_system.member.index', [
            'entMemberInfo' => $entMemberInfo,
            'keyword' => $keyword,
            'memberType'=>2
        ]);


    }


    /**
     * 修改会员界面
     * */
    public function edit(Request $request)
    {
        $this->check_role($request);
        $userId         = $request->input('userId',0);
        if($userId > 0)
        {
            $memberModel    = new MemberModel();
            $memberInfo     = $memberModel->get_member_info_by_id($userId);
            $memberInfo->personal_end_time = substr($memberInfo->personal_end_time,0,10);
            $orderprepaidlog=DB::table('vw_web_orderprepaidlog')
                ->select('ID','OrderNumber','AddDate','UserName','YourName')
                ->where('MemNumber',$memberInfo->MemNumber)
                ->get();

            //获得会员的学习官
            $sql = "SELECT d.UserID AS userId,d.YourName AS `name`
                FROM memberdrp a
                LEFT JOIN memberdrp   b ON b.DRPID      = a.ParentID
                LEFT JOIN memberinfo  d ON d.MemNumber  = b.MemNumber
                WHERE a.MemNumber = '{$memberInfo->MemNumber}'";
            $cloInfo    = DB::select($sql);
        }
        else
        {
            $memberInfo  = new \stdClass();
            $memberInfo->UserID = 0;
            $memberInfo->AppKey = "";
            $memberInfo->MemNumber = "";
            $memberInfo->NickName = "";
            $memberInfo->States = 0;
            $memberInfo->UserName = "";
            $memberInfo->YourName = "";
            $memberInfo->personal_end_time = "";
            $memberInfo->MemIntegral = 0;
            $cloInfo = false;
            $orderprepaidlog = [];
        }

        if($cloInfo) {
            $cloInfo    = $cloInfo[0];
        }
        else {
            $cloInfo    = new \stdClass();
            $cloInfo->userId    = 0;
            $cloInfo->name      = "";
        }


        $memberStates = [['value'=>0,'name'=>'未激活'],['value'=>1,'name'=>'已激活']];
        $data   = [
            'entMemberInfo' => $memberInfo,
            'memberStates'  => $memberStates,
            'cloInfo'       => $cloInfo,
            'orderlog'      => $orderprepaidlog
        ];
        return view('admin_system.member.edit', $data);
    }

    /**
     * 修改会员信息
     * */
    public function edit_action(Request $request)
    {
        $userId         = $request->input('userId');
        $mobile         = trim($request->get('mobile'));
        if($userId > 0)
        {
            $memberInfo = EntMemberInfo::find($userId);
        }
        else
        {
            $memberInfo = new EntMemberInfo();
            $memberInfo->RegisterType = "后台开通";
            $memberInfo->AddDate      = date_time();
        }

        $memberModel    = new MemberModel();
        DB::beginTransaction();
        //1.用户不存在
        if($userId == 0)
        {
            //检查号码是否存在
            $oldUser = $memberModel->get_member_info_by_mobile($mobile);
            if($oldUser){
                return apiData()->notice("用户{$mobile}已存在");
            }
            do{
                $MemNumber  = create_member_number();
                $oldUser = $memberModel->get_member_info_by_member_number($MemNumber);
            }while($oldUser != false);
            $memberInfo->MemNumber  = $MemNumber;
        }

        //检查学习官是否有效
        $cloUserId  = $request->input('cloUserId',0);
        $parentCloInfo    = false;
        if( $cloUserId > 0 )
        {
            $parentCloInfo    = $memberModel->get_member_drp_info($cloUserId);
            if(!$parentCloInfo)
            {
                return apiData()->notice('选择的学习官不是合格的学习官');
            }
        }

        $yourName               = trim($request->get('yourName'));
        $nickName               = trim($request->input('nickName'));
        $nickName               = $nickName ? $nickName :  $yourName;
        $memberInfo->States     = trim($request->get('states'));
        $memberInfo->UserName   = $mobile;
        $memberInfo->YourName   = $yourName;
        $memberInfo->NickName   = $nickName;
        $memberInfo->MemIntegral= trim($request->get('integral',0));
        $memberInfo->AppKey     = trim($request->get('appKey'));
        $memberInfo->ReleaseDate= date_time();
        $memberInfo->save();
        $userId     = $memberInfo->UserID;

        $memEndtime     = $request->input('memEndtime');
        if($memEndtime != $memberInfo->personal_end_time)
        {
            $memberModel->update_member_info(['UserID'=>$userId,'personal_end_time'=>$memEndtime]);
            $memberModel->change_member_endtime($userId);
        }


        if($parentCloInfo)
        {
            //查找自己是否存在drp表中
            $selfDrpInfo    = $memberModel->get_member_drp_info($userId);

            if($selfDrpInfo && $selfDrpInfo->MemNumber)
            {
                $oldIdTree  = $selfDrpInfo->IDTree;
                $newIdTree  = $parentCloInfo->IDTree.$selfDrpInfo->DRPID.".";
                //修改父级
                $entMemberDRP           = EntMemberDRP::find($selfDrpInfo->DRPID);
                $entMemberDRP->ParentID = $parentCloInfo->DRPID;
                $entMemberDRP->save();

                //修改下线
                $sql = "UPDATE memberdrp
                        SET IDTree = REPLACE(IDTree,'{$oldIdTree}','{$newIdTree}')
                        WHERE IDTree like  '{$oldIdTree}%'";
                DB::update($sql);
            }else{
                $entMemberDRP               = new EntMemberDRP();
                $entMemberDRP->MemNumber    = $memberInfo->MemNumber;
                $entMemberDRP->SalesMoney   = 0;
                $entMemberDRP->MemBalances  = 0;
                $entMemberDRP->FinishMoney  = 0;
                $entMemberDRP->DRPLevel     = 2;
                $entMemberDRP->IDTree       = '';
                $entMemberDRP->ParentID     = $parentCloInfo->DRPID;
                $entMemberDRP->MasterID     = '';
                $entMemberDRP->DeleteMark   = 1;
                $entMemberDRP->AddDate      = date('Y-m-d H:i:s', time());
                $entMemberDRP->IsRebate     = 1;
                $entMemberDRP->save();
                //修改idTree
                $drpId      = $entMemberDRP->DRPID;
                $idTree     = $parentCloInfo->IDTree.$drpId.".";
                DB::table('MemberDRP')->where('DRPID', $idTree)->update(['IDTree' => $idTree]);
            }
        }

        DB::commit();
        $result = $memberInfo ? '会员信息修改成功!' : '会员信息修改失败！' ;
        return redirect::back()->withInput()->withErrors($result);
    }


    /**
     * 添加会员页面
     * */
    public function createindex(Request $request){
        $this->check_role($request);
        return view('admin_system.member.indexAdd');
    }


    /**
     * 添加会员
     * */
    public function storeindex(Request $request){
        $memberModel    = new MemberModel();
        $apiData        = new ApiData();

        $mobile     = trim($request->get('mobile'));
        $userName   = trim($request->get('userName'));
        $endDate    = trim($request->get('endDate'));
        $params     = [
            'mobile'    => [$mobile,'缺少手机号',2001],
            'userNmae'  => [$userName,'缺少姓名',2002],
            'endDate'   => [$endDate,'缺少到期时间',2003]
        ];
        $checkResult = $this->check_params($params);
        if($checkResult->status == false){
            $apiData->code = $checkResult->code;
            $apiData->message   = $checkResult->message;
            return $apiData->send();
        }


        $memberInfo = $memberModel->get_member_info_by_mobile($mobile);
        if($memberInfo){
            $apiData->message   = "用户{$mobile}已存在";
            $apiData->code      = "401";
            return $apiData->send();
        }

        do{
            $MemNumber  = create_member_number();
            $memberInfo = $memberModel->get_member_info_by_member_number($MemNumber);
        }while($memberInfo != false);

        $userInfo = [
            'States'    => 1,
            'MemNumber' => $MemNumber,
            'UserName'  => $mobile,
            'YourName'  => $userName,
            'NickName'  => $userName,
            'VipNumber' => 1,
            'LoginKey'  => md5(date('YmdHis', time())),
            'MemEndTime'=> $endDate,
            'personal_end_time' => $endDate
        ];
        $memberModel->register($userInfo);
        $apiData->message   = "会员添加成功！";
        $apiData->code      = 200;
        return $apiData->send();
    }


    /**
     * 导入会员首页
     * */
    public function import_member_index(){

    }

    /**
     * 导入会员
     * */
    public function import_member(Request $request){
        return view('admin_system/member/import');
    }



    //批量添加会员
    public function add_members(Request $request){
        $companyId  = $request->input('companyId');
        $users      = $request->input('users');
        $users      = json_decode($users);
        $apiData    = new ApiData();
        $companyModel   = new CompanyModel();

        //检查公司是否存在
        $companyInfo    = $companyModel->get_company_info($companyId);
        if($companyInfo == false){
            $apiData->message   = "公司不存在";
            $apiData->code      = 4001;
            return $apiData->send();
        }

        //收集所有的部门
        $departments = $companyModel->get_company_department($companyId);
        $departs     = [];
        foreach($departments as $depart){
            $k = md5($depart->department_name);
            $departs[$k] = $depart->department_id;
        }


        $memberModel    = new MemberModel();
        $modifyNumber   = 0;
        $addNumber      = 0;
        $usePort        = 0;
        $errorMobiles   = [];
        foreach($users as $user){  //统一检测号码是否合格
            $mobile = $user->mobile;
            if(!($mobile && preg_match('/1\d{10}/',$mobile))){ //号码不符合
                array_push($errorMobiles,$mobile);
                continue;
            }
        }

        if(count($errorMobiles) > 0){
            $apiData->code = 4002;
            $apiData->message   = "号码异常:".implode(',',$errorMobiles);
//            return $apiData->send();
        }


        foreach($users as $user){
            //检查是否存在部门
            $userDepartment = $user->department;
            if(empty($userDepartment)){
                $departmentId = 0;
            }else{
                $key    = md5($userDepartment); //将部门名称作为key来处理
                if(isset($departs[$key])){ //已有部门
                    $departmentId   = $departs[$key];
                }else{ //创建新部门
                    $departmentId = $companyModel->update_department(['company_id'=>$companyId,'department_name'=>$userDepartment]);
                    $departs[$key] = $departmentId;
                }
            }

            $newUserInfo=[
                'States'    => 1,
                'MemEndTime'=> $companyInfo->vip_end_date,
            ];

            $mobile = $user->mobile;
            $memberInfo = $memberModel->get_member_info_by_mobile($mobile);

            if($memberInfo) //1.用户存在，修改用户信息
            { 
                $userId = $memberInfo->UserID;
                $modifyNumber++;

                if($companyModel->company_exists_member($companyId,$userId)) //1.1已属于该公司 修改
                { 
                    $companyMemberInfo  = [
                        'department_id'=>$departmentId,
                        'job'       => $user->job
                    ];
                    $companyModel->update_company_member($userId,$companyId,$companyMemberInfo);
                }
                else    //1.2 不属于公司
                {
                    $newUserInfo['UserID']      = $userId;
                    $memberModel->update_member_info($newUserInfo);
                    $companyModel->add_company_member($companyId,$departmentId,$userId,$user->job);
                    $usePort++;
                }
                $memberModel->change_member_endtime($userId);
            }
            else
            {
                 do{
                    $memberNumber   = create_member_number();
                    $tempInfo       = $memberModel->get_member_info_by_member_number($memberNumber);
                    $loop           = $tempInfo == false ? false : true;
                }while($loop);

                $userName = $user->username;
                $otherUserInfo = [
                    "MemNumber"     => $memberNumber,
                    "UserName"      => $mobile,
                    "NickName"      => $userName,
                    "YourName"      => $userName,
                    "RegisterType"  => 'system',
                    'AppKey'        => "",
                    "wx_unionid"    => "",
                    'app_openid'    => "",
                    'head_img'      => "",
                    'sex'           => "N",
                ];
                $data     = array_merge($newUserInfo,$otherUserInfo);
                $userId   = $memberModel->register($data);

                //加入公司
                $companyModel->add_company_member($companyId,$departmentId,$userId,$user->job);
                $usePort++;
                $addNumber++;
            }
        }
        //扣除公司的端口
        $companyModel->use_company_port($companyId,$usePort);
        $apiData->code    = 200;
        $apiData->message = "修改了{$modifyNumber}个老用户，添加了{$addNumber}个新用户";
        return $apiData->send();
    }


    public function test_create_qrcode() {
        $skip = Input::get('skip', 0);
        $member = EntMemberDRP::skip($skip)->take(500)->get();
        foreach ($member as $key => $value) {
            $url = 'http://wx.laohoulundao.com/parent/' . $value->DRPID . '.html';
            $qrcode = new BaconQrCodeGenerator;
            $qrcode->format('png')->size(300)->generate($url, public_path('/uploads/qrcode/' . $value->MemNumber . '.png'));
            dump($value->DRPID);
        }
    }



    public function indexdelete(Request $request)
    {
        $this->check_role($request);
        $result = '';
        try {
            if ($request->ajax()) {
                $IDList = $request->json('IDList');
                if (is_numeric($IDList)) {
                    EntMemberInfo::where('UserID', $IDList)->update([
                        'DeleteMark' => '0'
                    ]);
                    $result = 'ok';
                } else {
                    EntMemberInfo::whereIn('UserID', explode(',', $IDList))->update([
                        'DeleteMark' => '0'
                    ]);
                    $result = 'ok';
                }
            }
        } catch (Exception $e) {
            $result = 'no';
        }
        return $result;
    }



    /*
     * 选择用户
     * */
    public function select_member(Request $request){
        $companyId  = $request->input('companyId',0);
        return view('admin_system/member/select-member',['companyId'=>$companyId]);
    }

    /*
     * 选择用户的用户列表
     * */
    public function select_member_list(Request $request){
        $companyId  = $request->input('companyId');
        $keywords       = trim($request->input('keywords',''));
        if($companyId){
            $companyModel   = new CompanyModel();

            $members    = $companyModel->get_company_members($companyId,$keywords);
            $data = [
                     'entMemberInfo' => $members,
                     'keyword'       => $keywords,
                     'memberType'    => 0,
                     'registerType'  => 0,
                     'companyId'     => $companyId
                 ];
        }else{
            $data       = $this->get_index_data($request,$keywords,false);
        }
        return view('admin_system/member/select_member_list',$data);
    }


}
